package com.yzdbx.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.yzdbx.utils.DbUtil;
import com.yzdbx.utils.GenUtil;

import java.math.BigDecimal;
import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

import static com.yzdbx.utils.DbUtil.getMaxId;
import static com.yzdbx.utils.GenUtil.*;

/**
 * @BelongsProject: SERVEVICE-DATA-GEN
 * @BelongsPackage: com.yzdbx.task
 * @Author: lk
 * @CreateTime: 2025-05-14
 * @Description: TODO
 * @Version: 1.0
 */
@SuppressWarnings("all")
public class MaintenanceTaskRunnable implements Exe {


    private Connection connection;

    List<String> textileMaintenanceList = Arrays.asList(
            "设备内外清洁（清除纤维絮/油污，确保导轨/齿轮箱无积尘）",  //含漏油/漏气点检查:ml-citation{ref="1,4" data="citationList"}
            "润滑系统维护（按周期更换润滑油，检查油路通畅性）",  //需符合"五定"润滑标准:ml-citation{ref="3,5" data="citationList"}
            "紧固件状态检查（螺栓/皮带/链条松紧度调整）",  //重点检测传动部件连接点:ml-citation{ref="6,8" data="citationList"}
            "安全装置测试（急停按钮/防护罩/报警系统功能验证）",  //含制动装置灵敏度检测:ml-citation{ref="5,6" data="citationList"}
            "电气系统巡检（线路绝缘性/控制元件/接线端子状态）",  //避免短路或接触不良:ml-citation{ref="6,8" data="citationList"}
            "运行参数监控（轴承温度/振动幅度/噪音异常诊断）",  //建立基线数据对比:ml-citation{ref="6,7" data="citationList"}
            "易损件更换（针布/罗拉/皮圈等磨损件定期更新）",  //根据使用寿命预警:ml-citation{ref="1,4" data="citationList"}
            "工艺仪表校准（压力表/温控器/流量计精度校验）",  //影响产品质量的关键项:ml-citation{ref="6,7" data="citationList"}
            "气动液压系统检查（管路密封性/压力稳定性）",  //防止介质泄漏:ml-citation{ref="4,8" data="citationList"}
            "维保记录归档（异常情况/处理措施/更换配件登记）"  //形成可追溯文档:ml-citation{ref="1,6" data="citationList"}
    );


    public MaintenanceTaskRunnable(Connection connection) {
        this.connection = connection;
    }

    public boolean execute(int count) throws SQLException {
        LocalDate localDate = CUR_DATE.get();

        PreparedStatement statement = connection.prepareStatement("select * from wb01HealthInsuranceScheme");
        ResultSet resultSet = statement.executeQuery();
        List<LinkedHashMap<String, Object>> resultSetToList = DbUtil.resultSetToList(resultSet);

        if (CollectionUtil.isEmpty(resultSetToList)) {
            //初始化计划
            statement = connection.prepareStatement("select * from equipmentCounterStatements");
            List<LinkedHashMap<String, Object>> shebeiList = DbUtil.resultSetToList(statement.executeQuery());
            int id = 1;
            for (LinkedHashMap<String, Object> shebei : shebeiList) {
                statement = connection.prepareStatement("insert into wb01HealthInsuranceScheme(id,protectionPlanNumber,nameOfTheInsuranceScheme,nameOfTheSecurityDevice,protectionCycle,protectionContent,protector1,numberOfAssignmentsSent,nextVigilanceDate,faf2)values (?,?,?,?,?,?,?,?,?,?)");
                statement.setInt(1, id++);
                statement.setString(2, GenUtil.getNo("WB-", id++));
                statement.setString(3, shebei.get("f65e").toString() + "维保计划");
                statement.setString(4, shebei.get("f65e").toString());
                statement.setBigDecimal(5, BigDecimal.valueOf(90));
                statement.setString(6, RandomUtil.randomEle(textileMaintenanceList));
                statement.setString(7, shebei.get("responsiblePersons").toString());
                statement.setBigDecimal(8, BigDecimal.ONE);
                statement.setDate(9, GenUtil.ramdonDate());
                statement.setString(10, "启用");
                statement.execute();
            }

            statement = connection.prepareStatement("select * from wb01HealthInsuranceScheme where nextVigilanceDate = ?");
            statement.setDate(1, Date.valueOf(localDate));
            resultSetToList = DbUtil.resultSetToList(statement.executeQuery());

        }

        resultSetToList = resultSetToList.stream()
                .filter(map -> {
                    Object nextVigilanceDate = map.get("nextVigilanceDate");
                    return nextVigilanceDate != null && 
                           DateUtil.format((java.sql.Date) nextVigilanceDate, "yyyy-MM-dd").equals(localDate.toString());
                })
                .collect(Collectors.toList());

        if (CollectionUtil.isEmpty(resultSetToList)) return Boolean.TRUE;

        int id = getMaxId(connection, "by01MaintenanceSchedule");
        int num = 0;
        //维保任务开始时间递增 8------>

        for (LinkedHashMap<String, Object> map : resultSetToList) {
            long start = localDate.atStartOfDay(ZoneOffset.ofHours(8))
                    .toInstant()
                    .toEpochMilli() + 1000 * 60 * 60 * 8 + RandomUtil.randomLong(60000, 3600000);
            //查询到维保任务
            statement = connection.prepareStatement("insert into by01MaintenanceSchedule(id,wb1,scheduleNumber,equipment,numberOfEquipment,projectForTheProtectionOfTheEnvi,guards,otherOrganiser1,vipersTimeToStart,itsTheEndOfViva,itsTimeconsuming,workContentOfTheProtection) values (?,?,?,?,?,?,?,?,?,?,?,?)");
            statement.setInt(1, ++id);
            statement.setString(2, GenUtil.getNo("WBRW", ++num));
            statement.setString(3, map.get("id").toString());
            statement.setString(4, map.get("nameOfTheInsuranceScheme").toString());
            statement.setInt(5, 1);
            statement.setString(6, map.get("nameOfTheInsuranceScheme").toString());
            statement.setString(7, map.get("protector1").toString());
            statement.setTimestamp(9, new Timestamp(start));
            Timestamp end = new Timestamp(start + 1000 * 60 * 60 * 8);
            String state = System.currentTimeMillis() > end.getTime() ? "已完成" : "待维保";
            statement.setString(8, state);
            statement.setTimestamp(10, System.currentTimeMillis() > end.getTime() ? end : null);
            statement.setInt(11, "已完成".equals(state) ? 8 : 0);
            statement.setString(12, "日常维保");
            statement.execute();

            statement = connection.prepareStatement("update wb01HealthInsuranceScheme set numberOfAssignmentsSent = numberOfAssignmentsSent +? ,nextVigilanceDate = ? where id =?");
            statement.setInt(1, 1);
            statement.setDate(2, Date.valueOf(localDate.plusDays(Integer.parseInt(map.get("protectionCycle").toString()))));
            statement.setString(3, map.get("id").toString());
            statement.execute();
        }
        //更新维保状态
        statement = connection.prepareStatement("select * from by01MaintenanceSchedule where itsTheEndOfViva < ? and otherOrganiser1!=?");
        statement.setTimestamp(1, Timestamp.valueOf(LocalDateTime.now()));
        statement.setString(2, "已完成");
        resultSetToList = DbUtil.resultSetToList(statement.executeQuery());

        for (LinkedHashMap<String, Object> map : resultSetToList) {
            statement = connection.prepareStatement("update by01MaintenanceSchedule set otherOrganiser1 = ? ,itsTheEndOfViva=? ,itsTimeconsuming=? where id = ?");
            statement.setString(1, "已完成");
            statement.setTimestamp(2, new Timestamp(((Timestamp) map.get("vipersTimeToStart")).getTime() + 1000 * 60 * 60 * 8));
            statement.setInt(3, 8);
            statement.setString(4, map.get("id").toString());
            statement.execute();
        }
        return Boolean.TRUE;
    }


    public static void main(String[] args) {
        LocalDate start = MainTask.start;
        LocalDate end = MainTask.end;
        Connection conn = null;
        try {
            conn = DbUtil.getConnection();
            while (!start.isAfter(end)) {
                CUR_DATE.set(start);
                MaintenanceTaskRunnable maintenanceTaskRunnable = new MaintenanceTaskRunnable(conn);
                maintenanceTaskRunnable.execute(0);

                start = start.plusDays(1);
            }
            conn.commit();

        } catch (Exception ex) {
            try {
                conn.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } finally {
            DbUtil.closeConnection(conn);
        }
    }

}
